<template>
  <div class="writeoff-container">
    <!-- 顶部信息栏 -->
    <!-- 顶部信息栏 - 修改后 -->
    <div class="header-card bg-white rounded-lg shadow-md p-6 mb-8">
      <div
        class="flex flex-col md:flex-row items-start md:items-center justify-between gap-6"
      >
        <!-- 左侧字段组 - 修改后结构 -->
        <div class="flex-1 min-w-0 overflow-x-auto">
          <div
            class="flex items-center gap-4 flex-wrap md:flex-nowrap whitespace-nowrap"
          >
            <!-- 业务类型 -->
            <div class="flex items-center gap-2">
              <label class="required text-gray-700 font-medium"
                >业务类型：</label
              >
              <el-select
                v-model="businessType"
                @change="handleBusinessTypeChange"
                class="w-40"
              >
                <el-option
                  v-for="item in businessTypeOptions"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </div>

            <!-- 客户 -->
            <div class="flex items-center gap-2">
              <label class="required text-gray-700 font-medium">客户：</label>
              <el-input
                v-model="selectedCustomer.name"
                readonly
                @click="customerDialogVisible = true"
                class="w-40 cursor-pointer"
              />
            </div>

            <!-- 业务员 -->
            <div class="flex items-center gap-2">
              <label class="text-gray-700 font-medium">业务员：</label>
              <el-select v-model="salesman" class="w-32">
                <el-option
                  v-for="item in salesmanOptions"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </div>

            <!-- 单据日期 -->
            <div class="flex items-center gap-2">
              <label class="required text-gray-700 font-medium"
                >单据日期：</label
              >
              <el-date-picker
                v-model="docDate"
                value-format="YYYY-MM-DD"
                class="w-32"
              />
            </div>
          </div>
        </div>

        <!-- 右侧：附件 + 单据编号（保持不变） -->
        <div class="flex flex-col gap-2">
          <el-upload
            action="#"
            :file-list="attachments"
            @preview="handlePreview"
          >
            <el-button
              type="text"
              class="text-blue-600 hover:text-blue-800 flex items-center"
            >
              <el-icon><UploadFilled /></el-icon>
              <span class="ml-1">上传附件</span>
            </el-button>
          </el-upload>
          <span class="text-gray-600">单据编号：{{ docNo }}</span>
        </div>
      </div>
    </div>

    <!-- 源单表格区域（预收冲应收 + 应收单据） -->
    <div class="grid grid-cols-1 gap-8">
      <!-- 预收冲应收表格 -->
      <div class="bg-white rounded-lg shadow-md p-6 overflow-x-auto">
        <div class="flex justify-between items-center mb-6">
          <h3 class="text-xl font-semibold">预收冲应收</h3>
          <div class="flex gap-2">
            <el-button
              type="primary"
              @click="openPreCollectionSourceDialog"
              class="text-sm"
              >选择预收单据</el-button
            >
            <el-button type="success" @click="autoSettle('pre')" class="text-sm"
              >自动核销</el-button
            >
          </div>
        </div>
        <el-table
          :data="preCollectionTable"
          border
          stripe
          class="text-sm"
          style="width: 100%; min-width: 1200px"
        >
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <div class="flex items-center justify-center gap-1">
                <!-- 新增行（绿色按钮，无图标） -->
                <el-button
                  type="success"
                  @click="addPreCollectionRow(scope.$index)"
                  size="mini"
                  text
                  hover-effect="light"
                  class="px-2 py-1"
                  >添加</el-button
                >
                <!-- 删除行（红色按钮，无图标） -->
                <el-button
                  type="danger"
                  @click="deletePreCollectionRow(scope.row)"
                  size="mini"
                  text
                  hover-effect="light"
                  class="px-2 py-1"
                  >删除</el-button
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column label="源单编号" prop="sourceNo" width="120" />
          <el-table-column label="业务类别" prop="businessType" width="100" />
          <el-table-column label="单据日期" prop="docDate" width="120" />
          <el-table-column
            label="单据金额"
            prop="docAmount"
            width="100"
            align="right"
          >
            <template #default="scope">
              ¥{{ scope.row.docAmount.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column
            label="已核销金额"
            prop="settledAmount"
            width="100"
            align="right"
          >
            <template #default="scope">
              ¥{{ scope.row.settledAmount.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column
            label="未核销金额"
            prop="unsettledAmount"
            width="100"
            align="right"
          >
            <template #default="scope">
              ¥{{ scope.row.unsettledAmount.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column label="源单备注" prop="sourceRemark" width="150" />
          <el-table-column
            label="*本次核销金额"
            prop="currentSettle"
            width="120"
            align="right"
          >
            <template #default="scope">
              <el-input
                v-model.number="scope.row.currentSettle"
                type="number"
                size="small"
                required
              />
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" width="150" />
          <template #footer>
            <el-table-row>
              <el-table-cell>合计：</el-table-cell>
              <el-table-cell colspan="6" align="right">
                ¥{{ preCollectionTotal.toFixed(2) }}
              </el-table-cell>
            </el-table-row>
          </template>
        </el-table>
      </div>

      <!-- 应收单据表格 -->
      <div class="bg-white rounded-lg shadow-md p-6 overflow-x-auto">
        <div class="flex justify-between items-center mb-6">
          <h3 class="text-xl font-semibold">应收单据</h3>
          <div class="flex gap-2">
            <el-button
              type="primary"
              @click="openReceivableSourceDialog"
              class="text-sm"
              >选择应收单据</el-button
            >
            <el-button
              type="success"
              @click="autoSettle('receivable')"
              class="text-sm"
              >自动核销</el-button
            >
          </div>
        </div>
        <el-table
          :data="receivableTable"
          border
          stripe
          class="text-sm"
          style="width: 100%; min-width: 1200px"
        >
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <div class="flex items-center justify-center gap-1">
                <!-- 新增行（绿色按钮，无图标） -->
                <el-button
                  type="success"
                  @click="addReceivableRow(scope.$index)"
                  size="mini"
                  text
                  hover-effect="light"
                  class="px-2 py-1"
                  >添加</el-button
                >
                <!-- 删除行（红色按钮，无图标） -->
                <el-button
                  type="danger"
                  @click="deleteReceivableRow(scope.row)"
                  size="mini"
                  text
                  hover-effect="light"
                  class="px-2 py-1"
                  >删除</el-button
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column label="源单编号" prop="sourceNo" width="120" />
          <el-table-column label="业务类别" prop="businessType" width="100" />
          <el-table-column label="单据日期" prop="docDate" width="120" />
          <el-table-column
            label="单据金额"
            prop="docAmount"
            width="100"
            align="right"
          >
            <template #default="scope">
              ¥{{ scope.row.docAmount.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column
            label="已核销金额"
            prop="settledAmount"
            width="100"
            align="right"
          >
            <template #default="scope">
              ¥{{ scope.row.settledAmount.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column
            label="未核销金额"
            prop="unsettledAmount"
            width="100"
            align="right"
          >
            <template #default="scope">
              ¥{{ scope.row.unsettledAmount.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column label="源单备注" prop="sourceRemark" width="150" />
          <el-table-column
            label="*本次核销金额"
            prop="currentSettle"
            width="120"
            align="right"
          >
            <template #default="scope">
              <el-input
                v-model.number="scope.row.currentSettle"
                type="number"
                size="small"
                required
              />
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" width="150" />
          <template #footer>
            <el-table-row>
              <el-table-cell>合计：</el-table-cell>
              <el-table-cell colspan="6" align="right">
                ¥{{ receivableTotal.toFixed(2) }}
              </el-table-cell>
            </el-table-row>
          </template>
        </el-table>
      </div>
    </div>

    <!-- 底部备注 + 操作栏 -->
    <div class="mt-8 bg-white rounded-lg shadow-md p-6">
      <el-form label-width="80px">
        <el-form-item label="备注信息">
          <el-input
            type="textarea"
            v-model="remark"
            placeholder="暂无备注信息"
            class="h-16"
          />
        </el-form-item>
        <div class="flex justify-end gap-2">
          <el-button type="primary" class="text-sm">保存并新增</el-button>
          <el-button type="success" class="text-sm">保存</el-button>
          <el-button type="info" class="text-sm">审核</el-button>
          <el-button type="text" class="text-sm text-gray-600"
            >历史单据</el-button
          >
          <el-button type="text" class="text-sm text-gray-600"
            >操作日志</el-button
          >
        </div>
      </el-form>
    </div>

    <!-- 客户选择弹窗 -->
    <el-dialog
      title="选择客户"
      v-model="customerDialogVisible"
      width="800px"
      class="dialog-custom"
    >
      <el-form :model="customerQuery" inline label-width="80px" class="mb-4">
        <el-form-item label="类别">
          <el-select v-model="customerQuery.category" size="small">
            <el-option label="华中地区" value="central"></el-option>
            <el-option label="华北地区" value="north"></el-option>
            <el-option label="华南地区" value="south"></el-option>
            <el-option label="批发" value="wholesale"></el-option>
            <el-option label="广东省内" value="guangdong"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="查询">
          <el-input
            v-model="customerQuery.keyword"
            placeholder="编号/名称/联系人/电话"
            size="small"
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="customerQuery.showDisabled" size="small">
            显示禁用客户
          </el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchCustomers" size="small">
            查询
          </el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="customerList"
        border
        stripe
        @selection-change="handleCustomerSelection"
        class="text-sm"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="类别" prop="category" width="100" />
        <el-table-column label="编号" prop="code" width="120" />
        <el-table-column label="名称" prop="name" width="180" />
        <el-table-column label="联系人" prop="contact" width="100" />
        <el-table-column label="手机" prop="phone" width="120" />
        <el-table-column label="备注" prop="remark" width="150" />
      </el-table>
      <div class="dialog-footer flex justify-between items-center mt-4">
        <el-pagination
          @size-change="(val) => (customerPageSize = val)"
          @current-change="(val) => (customerPage = val)"
          :current-page="customerPage"
          :page-sizes="[10, 50, 100]"
          :page-size="customerPageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="customerTotal"
          size="small"
        />
        <div class="flex gap-2">
          <el-button @click="customerDialogVisible = false" size="small">
            取消
          </el-button>
          <el-button type="primary" @click="confirmCustomer" size="small">
            确定
          </el-button>
          <el-button
            type="text"
            size="small"
            class="text-blue-600 hover:text-blue-800"
            @click="openAddCustomerDialog"
          >
            新增客户
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 新增客户弹窗 -->
    <el-dialog
      title="新增客户"
      v-model="addCustomerDialogVisible"
      width="600px"
      class="dialog-custom"
    >
      <el-form :model="newCustomer" label-width="100px" class="p-4">
        <el-form-item label="*类别" prop="category">
          <el-input v-model="newCustomer.category" size="small" required />
        </el-form-item>
        <el-form-item label="*编号" prop="code">
          <el-input v-model="newCustomer.code" size="small" required />
        </el-form-item>
        <el-form-item label="*名称" prop="name">
          <el-input v-model="newCustomer.name" size="small" required />
        </el-form-item>
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="newCustomer.contact" size="small" />
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="newCustomer.phone" size="small" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="newCustomer.remark" size="small" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex justify-end gap-2">
          <el-button @click="addCustomerDialogVisible = false" size="small">
            取消
          </el-button>
          <el-button type="primary" @click="saveNewCustomer" size="small">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选择预收单据弹窗（模拟） -->
    <el-dialog
      title="选择预收单据"
      v-model="preCollectionSourceDialogVisible"
      width="900px"
      class="dialog-custom"
    >
      <el-form :model="preSourceQuery" inline label-width="80px" class="mb-4">
        <el-form-item label="业务类型">
          <el-select v-model="preSourceQuery.businessType" size="small">
            <el-option label="预收" value="pre"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="preSourceQuery.dateRange"
            type="daterange"
            range-separator="至"
            size="small"
          />
        </el-form-item>
        <el-form-item label="查询">
          <el-input
            v-model="preSourceQuery.keyword"
            placeholder="单号/客户"
            size="small"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchPreSources" size="small">
            查询
          </el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="preSourceList"
        border
        stripe
        @selection-change="handlePreSourceSelection"
        class="text-sm"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="单据编号" prop="sourceNo" width="120" />
        <el-table-column label="业务类型" prop="businessType" width="100" />
        <el-table-column label="单据日期" prop="docDate" width="120" />
        <el-table-column
          label="单据金额"
          prop="docAmount"
          width="100"
          align="right"
        >
          <template #default="scope">
            ¥{{ scope.row.docAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column
          label="已核销金额"
          prop="settledAmount"
          width="100"
          align="right"
        >
          <template #default="scope">
            ¥{{ scope.row.settledAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column
          label="未核销金额"
          prop="unsettledAmount"
          width="100"
          align="right"
        >
          <template #default="scope">
            ¥{{ scope.row.unsettledAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="单据状态" prop="status" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)" size="mini">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div class="dialog-footer flex justify-between items-center mt-4">
        <el-pagination
          @size-change="(val) => (preSourcePageSize = val)"
          @current-change="(val) => (preSourcePage = val)"
          :current-page="preSourcePage"
          :page-sizes="[10, 50, 100]"
          :page-size="preSourcePageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="preSourceTotal"
          size="small"
        />
        <div class="flex gap-2">
          <el-button
            @click="preCollectionSourceDialogVisible = false"
            size="small"
          >
            取消
          </el-button>
          <el-button type="primary" @click="confirmPreSource" size="small">
            确定
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 选择应收单据弹窗（模拟） -->
    <el-dialog
      title="选择应收单据"
      v-model="receivableSourceDialogVisible"
      width="900px"
      class="dialog-custom"
    >
      <el-form
        :model="receivableSourceQuery"
        inline
        label-width="80px"
        class="mb-4"
      >
        <el-form-item label="业务类型">
          <el-select v-model="receivableSourceQuery.businessType" size="small">
            <el-option label="应收" value="receivable"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="receivableSourceQuery.dateRange"
            type="daterange"
            range-separator="至"
            size="small"
          />
        </el-form-item>
        <el-form-item label="查询">
          <el-input
            v-model="receivableSourceQuery.keyword"
            placeholder="单号/客户"
            size="small"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="fetchReceivableSources"
            size="small"
          >
            查询
          </el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="receivableSourceList"
        border
        stripe
        @selection-change="handleReceivableSourceSelection"
        class="text-sm"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="单据编号" prop="sourceNo" width="120" />
        <el-table-column label="业务类型" prop="businessType" width="100" />
        <el-table-column label="单据日期" prop="docDate" width="120" />
        <el-table-column
          label="单据金额"
          prop="docAmount"
          width="100"
          align="right"
        >
          <template #default="scope">
            ¥{{ scope.row.docAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column
          label="已核销金额"
          prop="settledAmount"
          width="100"
          align="right"
        >
          <template #default="scope">
            ¥{{ scope.row.settledAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column
          label="未核销金额"
          prop="unsettledAmount"
          width="100"
          align="right"
        >
          <template #default="scope">
            ¥{{ scope.row.unsettledAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="单据状态" prop="status" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)" size="mini">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div class="dialog-footer flex justify-between items-center mt-4">
        <el-pagination
          @size-change="(val) => (receivableSourcePageSize = val)"
          @current-change="(val) => (receivableSourcePage = val)"
          :current-page="receivableSourcePage"
          :page-sizes="[10, 50, 100]"
          :page-size="receivableSourcePageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="receivableSourceTotal"
          size="small"
        />
        <div class="flex gap-2">
          <el-button
            @click="receivableSourceDialogVisible = false"
            size="small"
          >
            取消
          </el-button>
          <el-button
            type="primary"
            @click="confirmReceivableSource"
            size="small"
          >
            确定
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import {
  ElDialog,
  ElTable,
  ElTableColumn,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElDatePicker,
  ElButton,
  ElTag,
  ElPagination,
  ElUpload,
  ElMessage,
  ElIcon,
} from "element-plus";
import { UploadFilled } from "@element-plus/icons-vue";

// 业务类型
const businessTypeOptions = ref([
  "预收冲应收",
  "预付冲应付",
  "应收冲应付",
  "应收转应收",
  "应付转应付",
]);
const businessType = ref("预收冲应收");

// 客户信息
const selectedCustomer = ref({ name: "" });
const customerDialogVisible = ref(false);
const customerQuery = reactive({
  category: "",
  keyword: "",
  showDisabled: false,
});
const customerList = ref([
  {
    category: "华中地区",
    code: "1000000",
    name: "客户1",
    contact: "张",
    phone: "159****1234",
    remark: "",
  },
  {
    category: "华北地区",
    code: "1000001",
    name: "客户2",
    contact: "李先生",
    phone: "183****0000",
    remark: "",
  },
  {
    category: "华北地区",
    code: "1000002",
    name: "客户3",
    contact: "王",
    phone: "182****1234",
    remark: "",
  },
  {
    category: "华南地区",
    code: "1000003",
    name: "客户4-罗",
    contact: "赵",
    phone: "182****1234",
    remark: "",
  },
  {
    category: "批发",
    code: "1000004",
    name: "客户5",
    contact: "马路",
    phone: "183****0000",
    remark: "",
  },
  {
    category: "广东省内",
    code: "1000005",
    name: "客户6",
    contact: "周",
    phone: "180****0000",
    remark: "",
  },
  {
    category: "华中地区",
    code: "1000006",
    name: "客户7",
    contact: "吴",
    phone: "182****1234",
    remark: "",
  },
  {
    category: "批发",
    code: "1000007",
    name: "客户8",
    contact: "郑",
    phone: "159****1234",
    remark: "",
  },
  {
    category: "华中地区",
    code: "1000008",
    name: "客户9",
    contact: "王",
    phone: "175****1234",
    remark: "",
  },
]);
const customerTotal = ref(17);
const customerPage = ref(1);
const customerPageSize = ref(10);
const newCustomer = reactive({
  category: "",
  code: "",
  name: "",
  contact: "",
  phone: "",
  remark: "",
});
const addCustomerDialogVisible = ref(false);

// 业务员
const salesmanOptions = ref([
  "(空)",
  "老板",
  "财务-玲",
  "采购-小陈",
  "采购-小王",
  "销售-小李",
]);
const salesman = ref("(空)");

// 单据信息
const docDate = ref(new Date().toISOString().slice(0, 10));
const docNo = ref("HXO20250625001");
const attachments = ref([]);
const remark = ref("");

// 源单表格数据（预收冲应收 + 应收）
const preCollectionTable = ref([
  {
    id: 1,
    sourceNo: "",
    businessType: "",
    docDate: "",
    docAmount: 0,
    settledAmount: 0,
    unsettledAmount: 0,
    sourceRemark: "",
    currentSettle: 0,
    remark: "",
  },
]);
const receivableTable = ref([
  {
    id: 1,
    sourceNo: "",
    businessType: "",
    docDate: "",
    docAmount: 0,
    settledAmount: 0,
    unsettledAmount: 0,
    sourceRemark: "",
    currentSettle: 0,
    remark: "",
  },
]);

// 选择源单弹窗（模拟数据）
const preCollectionSourceDialogVisible = ref(false);
const preSourceQuery = reactive({});
const preSourceList = ref([
  {
    sourceNo: "PRE20250601",
    businessType: "预收",
    docDate: "2025-06-01",
    docAmount: 5000,
    settledAmount: 0,
    unsettledAmount: 5000,
    status: "unsettled",
  },
]);
const preSourceTotal = ref(10);
const preSourcePage = ref(1);
const preSourcePageSize = ref(10);
const selectedPreSources = ref([]);

const receivableSourceDialogVisible = ref(false);
const receivableSourceQuery = reactive({});
const receivableSourceList = ref([
  {
    sourceNo: "REC20250602",
    businessType: "应收",
    docDate: "2025-06-02",
    docAmount: 8000,
    settledAmount: 0,
    unsettledAmount: 8000,
    status: "unsettled",
  },
]);
const receivableSourceTotal = ref(10);
const receivableSourcePage = ref(1);
const receivableSourcePageSize = ref(10);
const selectedReceivableSources = ref([]);

// 合计计算
const preCollectionTotal = computed(() =>
  preCollectionTable.value.reduce((sum, item) => sum + item.currentSettle, 0)
);
const receivableTotal = computed(() =>
  receivableTable.value.reduce((sum, item) => sum + item.currentSettle, 0)
);

// 辅助方法
const getStatusLabel = (value) => {
  const map = {
    unsettled: "未核销",
    partial: "部分核销",
    settled: "已核销",
  };
  return map[value] || value;
};
const getStatusType = (value) => {
  const map = {
    unsettled: "danger",
    partial: "warning",
    settled: "success",
  };
  return map[value] || "default";
};

// 业务类型切换
const handleBusinessTypeChange = (val) => {
  // 可扩展：根据业务类型加载不同数据
  console.log("切换业务类型：", val);
};

// 客户相关方法
const fetchCustomers = () => {
  // 模拟接口请求（实际需对接后端）
  console.log("查询客户：", customerQuery);
};
const handleCustomerSelection = (val) => {
  selectedCustomer.value = val[0] || {};
};
const confirmCustomer = () => {
  customerDialogVisible.value = false;
};
const openAddCustomerDialog = () => {
  addCustomerDialogVisible.value = true;
};
const saveNewCustomer = () => {
  if (!newCustomer.category || !newCustomer.code || !newCustomer.name) {
    ElMessage.warning("类别、编号、名称为必填项！");
    return;
  }
  customerList.value.push({ ...newCustomer });
  ElMessage.success("客户添加成功！");
  addCustomerDialogVisible.value = false;
};

// 表格操作方法
const addPreCollectionRow = (index) => {
  preCollectionTable.value.splice(index + 1, 0, {
    id: preCollectionTable.value.length + 1,
    sourceNo: "",
    businessType: "",
    docDate: "",
    docAmount: 0,
    settledAmount: 0,
    unsettledAmount: 0,
    sourceRemark: "",
    currentSettle: 0,
    remark: "",
  });
};
const deletePreCollectionRow = (row) => {
  preCollectionTable.value = preCollectionTable.value.filter(
    (item) => item.id !== row.id
  );
};

const addReceivableRow = (index) => {
  receivableTable.value.splice(index + 1, 0, {
    id: receivableTable.value.length + 1,
    sourceNo: "",
    businessType: "",
    docDate: "",
    docAmount: 0,
    settledAmount: 0,
    unsettledAmount: 0,
    sourceRemark: "",
    currentSettle: 0,
    remark: "",
  });
};
const deleteReceivableRow = (row) => {
  receivableTable.value = receivableTable.value.filter(
    (item) => item.id !== row.id
  );
};

// 选择源单方法
const openPreCollectionSourceDialog = () => {
  preCollectionSourceDialogVisible.value = true;
  fetchPreSources();
};
const fetchPreSources = () => {
  // 模拟加载预收单据（实际需对接后端）
  console.log("查询预收单据：", preSourceQuery);
};
const handlePreSourceSelection = (val) => {
  selectedPreSources.value = val;
};
const confirmPreSource = () => {
  selectedPreSources.value.forEach((source) => {
    const exists = preCollectionTable.value.some(
      (item) => item.sourceNo === source.sourceNo
    );
    if (!exists) {
      preCollectionTable.value.push({
        id: preCollectionTable.value.length + 1,
        sourceNo: source.sourceNo,
        businessType: source.businessType,
        docDate: source.docDate,
        docAmount: source.docAmount,
        settledAmount: source.settledAmount,
        unsettledAmount: source.unsettledAmount,
        sourceRemark: "",
        currentSettle: 0,
        remark: "",
      });
    }
  });
  preCollectionSourceDialogVisible.value = false;
};

const openReceivableSourceDialog = () => {
  receivableSourceDialogVisible.value = true;
  fetchReceivableSources();
};
const fetchReceivableSources = () => {
  // 模拟加载应收单据（实际需对接后端）
  console.log("查询应收单据：", receivableSourceQuery);
};
const handleReceivableSourceSelection = (val) => {
  selectedReceivableSources.value = val;
};
const confirmReceivableSource = () => {
  selectedReceivableSources.value.forEach((source) => {
    const exists = receivableTable.value.some(
      (item) => item.sourceNo === source.sourceNo
    );
    if (!exists) {
      receivableTable.value.push({
        id: receivableTable.value.length + 1,
        sourceNo: source.sourceNo,
        businessType: source.businessType,
        docDate: source.docDate,
        docAmount: source.docAmount,
        settledAmount: source.settledAmount,
        unsettledAmount: source.unsettledAmount,
        sourceRemark: "",
        currentSettle: 0,
        remark: "",
      });
    }
  });
  receivableSourceDialogVisible.value = false;
};

// 自动核销（模拟逻辑：将未核销金额全选）
const autoSettle = (type) => {
  if (type === "pre") {
    preCollectionTable.value.forEach((row) => {
      row.currentSettle = row.unsettledAmount;
    });
  } else {
    receivableTable.value.forEach((row) => {
      row.currentSettle = row.unsettledAmount;
    });
  }
  ElMessage.info("自动核销完成！");
};

// 附件预览
const handlePreview = (file) => {
  ElMessage.info(`预览附件：${file.name}`);
};

onMounted(() => {
  fetchCustomers();
});
</script>

<style scoped>
.writeoff-container {
  padding: 32px;
  background: #f9fafb;
}
.header-card {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border-radius: 12px;
}
.required::after {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}
.el-table {
  --el-table-header-text-color: #303133;
  --el-table-header-background-color: #f5f7fa;
  --el-table-row-hover-background-color: #f0f2f5;
}
.el-table__cell {
  white-space: nowrap;
  overflow: visible;
  text-overflow: clip;
}
.overflow-x-auto {
  overflow-x: auto;
}
::-webkit-scrollbar {
  height: 6px;
  width: 6px;
}
::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}
::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
@media (max-width: 1024px) {
  .writeoff-container {
    padding: 16px;
  }
  .header-card .flex {
    flex-direction: column;
    gap: 4px;
  }
  .header-card .flex > div {
    min-width: 100%;
  }
}
</style>